package com.mashibing.tank;

import java.awt.Graphics;
import java.awt.Rectangle;

/**
 * Copyright (C) 2024 - 2024 Jasonakeke， Inc. All Rights Reserved
 *
 * @Desc :
 * @Time : 2024/10/3 17:43
 * @Author : Code_By_Jasonakeke
 * @Email : 2284037977@qq.com
 * @Class : Bullet
 * @IDE : IntelliJ IDEA
 */
public class Bullet {

	private static final int SPEED = Integer.parseInt((String) PropertyMgr.get("bulletSpeed"));

	public static final int WIDTH = ResourceMgr.bulletD.getWidth();

	public static final int HEIGHT = ResourceMgr.bulletD.getHeight();

	private Rectangle rect = new Rectangle();

	private int x;

	private int y;

	private Dir dir;

	private boolean living = true;

	private TankFrame tankFrame;

	private Group group = Group.BAD;

	public Bullet(int x, int y, Dir dir, Group group, TankFrame tankFrame) {
		this.x = x;
		this.y = y;
		this.dir = dir;
		this.group = group;
		this.tankFrame = tankFrame;

		rect.x = x;
		rect.y = y;
		rect.width = WIDTH;
		rect.height = HEIGHT;
	}

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	public void paint(Graphics g) {
		if (!living) {
			tankFrame.getBullets().remove(this);
		}
		switch (dir) {
			case LEFT:
				g.drawImage(ResourceMgr.bulletL, x, y, null);
				break;
			case RIGHT:
				g.drawImage(ResourceMgr.bulletR, x, y, null);
				break;
			case UP:
				g.drawImage(ResourceMgr.bulletU, x, y, null);
				break;
			case DOWN:
				g.drawImage(ResourceMgr.bulletD, x, y, null);
				break;
		}

		move();
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public Dir getDir() {
		return dir;
	}

	public void setDir(Dir dir) {
		this.dir = dir;
	}

	public boolean isLiving() {
		return living;
	}

	public void setLiving(boolean living) {
		this.living = living;
	}

	public TankFrame getTankFrame() {
		return tankFrame;
	}

	public void setTankFrame(TankFrame tankFrame) {
		this.tankFrame = tankFrame;
	}

	public void move() {
		switch (dir) {
			case LEFT:
				x -= SPEED;
				break;
			case RIGHT:
				x += SPEED;
				break;
			case UP:
				y -= SPEED;
				break;
			case DOWN:
				y += SPEED;
				break;
			default:
				break;
		}
		// update rect
		rect.x = x;
		rect.y = y;
		if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {
			living = false;
		}
	}

	public void collideWith(Tank tank) {
		if (getGroup() == tank.getGroup()) {
			return;
		}
		// TODO：用一个 rect 来记录子弹的位置
		if (rect.intersects(tank.getRect())){
			tank.die();
			die();
			int eX = tank.getX() + Tank.getWIDTH() / 2 - Explode.WIDTH / 2;
			int eY = tank.getY() + Tank.getHEIGHT() / 2 - Explode.HEIGHT / 2;
			tankFrame.explodes.add(new Explode(eX, eY, tankFrame));
		}
	}

	private void die() {
		living = false;
	}
}
